package com.bree.erp.service.stateless;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.apache.log4j.Logger;

import com.bree.erp.entity.PartUnit;
import com.bree.erp.entity.Price;
import com.bree.erp.entity.Supplier;
import com.bree.erp.service.PriceService;

@Stateless
public class PriceServiceBean implements PriceService {

	private static Logger LOG = Logger.getLogger(PriceServiceBean.class);
			
	@PersistenceContext()
	private EntityManager em;

	@Override
	public Price create(Long partUnitId, Long supplierId, double pricePerUnit) {

		Price price = new Price();

		PartUnit partUnit = em.find(PartUnit.class, partUnitId);
		Supplier supplier = em.find(Supplier.class, supplierId);

		price.setPartUnit(partUnit);
		price.setSupplier(supplier);
		price.setPricePerUnit(pricePerUnit);

		em.persist(price);

		return price;
	}

	@Override
	public Price read(Long id) {
		Price price = em.find(Price.class, id);
		return price;
	}

	@Override
	public Price update(Long id, String remarks) {
		Price price = read(id);

		price.setRemarks(remarks);

		return price;
	}

	@Override
	public void delete(Long id) {

		Price price = read(id);

		em.remove(price);
	}

	@Override
	public Price read(Long partUnitId, Long supplierId) {

		PartUnit partUnit = em.find(PartUnit.class, partUnitId);
		Supplier supplier = em.find(Supplier.class, supplierId);

		TypedQuery<Price> query = em
				.createNamedQuery(Price.QUERY_GET_UNITPRICE_OF_SUPPLIER,
						Price.class).setParameter("partUnit", partUnit)
				.setParameter("supplier", supplier);
		try {
			return query.getSingleResult();
		} catch (NoResultException e) {
			LOG.warn(e.getMessage());
			return null;
		}
	}

	@Override
	public Price update(Long id, double unitPrice) {
		
		Price price = read(id);
		price.setPricePerUnit(unitPrice);
		
		return price;
		
	}

}
